package com.shuaidong.site.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.shuaidong.site.entity.SysMenu;
import com.shuaidong.site.entity.vo.TreeMenu;
import com.shuaidong.site.entity.vo.TreeMenuAllowAccess;
import com.shuaidong.site.mapper.SysMenuMapper;
import com.shuaidong.site.mapper.SysRoleMenuMapper;
import com.shuaidong.site.service.ISysMenuService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author td
 * @date 2017/12/21
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper,SysMenu> implements ISysMenuService {

    /**
     * 菜单服务
     */
    @Autowired
    private SysMenuMapper sysMenuMapper;


    /**
     * 角色菜单关系服务
     */
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    /**
     *
     * @param uid 用户id
     * @return
     */
    @Override
    public List<String> selectMenuIdsByUserId(String uid) {

        return sysMenuMapper.selectMenuIdsByuserId(uid);

    }


    @Override
    public List<TreeMenu> selectTreeMenuByMenuIdsAndPid (List<String> menuIds, String pid) {
        // 判断menuIds是否有值,随机生成一个值放在里面
        menuIds = menuIds.size()>0 ? menuIds: Lists.newArrayList(RandomStringUtils.randomNumeric(30));
        // 获取菜单
        List<SysMenu> sysMenuList = sysMenuMapper.selectMenusByMenuIdsAndPid(menuIds,pid);

        List<TreeMenu> treeMenuList = new ArrayList<TreeMenu>();

        for (SysMenu sysMenu:sysMenuList) {
            TreeMenu treeMenu = new TreeMenu();
            treeMenu.setSysMenu(sysMenu);

            if (sysMenu.getDeep()<2) {
                // 使用递归生成菜单树
                treeMenu.setChildren(this.selectTreeMenuByMenuIdsAndPid(menuIds, sysMenu.getId()));
            }
            treeMenuList.add(treeMenu);

        }
        return treeMenuList;
    }

    @Override
    public List<TreeMenu> selectTreeMenuByUserId(String uid) {

        //通过用户uid获取用户角色权限
        List<String> roleMenuIds = sysRoleMenuMapper.selectRoleMenuIdsByUserId(uid);

        // 根据用户角色权限查询用户菜单
        return this.selectTreeMenuByMenuIdsAndPid(roleMenuIds,"0");

    }

    @Override
    public List<TreeMenuAllowAccess> selectTreeAllowAccessByMenuIdsAndPid(List<String> menuIds, String pid) {
        return null;
    }
}
